<template>
  <div class="project-flow-selector">
    <!-- 触发按钮 -->
    <el-input v-model="displayText" :placeholder="placeholder" :disabled="disabled" readonly @click="openDialog" style="cursor: pointer">
      <template #suffix>
        <el-icon><ArrowDown /></el-icon>
      </template>
    </el-input>

    <!-- 选择对话框 -->
    <el-dialog v-model="dialogVisible" title="选择项目流程" width="1000px" :before-close="handleClose" append-to-body>
      <div class="selector-container">
        <!-- 左侧：项目列表 -->
        <div class="project-section">
          <div class="section-header">
            <h3>项目列表</h3>
            <el-input v-model="projectSearchKeyword" placeholder="搜索项目名称" clearable style="width: 200px" @input="handleProjectSearch">
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>

          <div class="project-list" v-loading="projectLoading">
            <el-scrollbar height="400px">
              <div
                v-for="project in filteredProjects"
                :key="project.id"
                class="project-item"
                :class="{ active: selectedProject?.id === project.id }"
                @click="selectProject(project)"
              >
                <div class="project-info">
                  <div class="project-name">{{ project.proName }}</div>
                  <div class="project-number">{{ project.proNumber }}</div>
                  <div class="project-meta">
                    <span class="project-amount">项目类型：</span>
                    <dict-tag :options="project_type" :value="project.proType" />
                  </div>
                </div>
                <el-icon v-if="selectedProject?.id === project.id" class="selected-icon">
                  <Check />
                </el-icon>
              </div>
            </el-scrollbar>
          </div>
        </div>

        <!-- 右侧：流程列表 -->
        <div class="flow-section">
          <div class="section-header">
            <h3>项目流程</h3>
            <el-input
              v-model="flowSearchKeyword"
              placeholder="搜索流程名称"
              clearable
              style="width: 200px"
              @input="handleFlowSearch"
              :disabled="!selectedProject"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>

          <div class="flow-list" v-loading="flowLoading">
            <el-scrollbar height="400px">
              <el-empty v-if="!selectedProject" description="请先选择项目" />
              <div v-else-if="filteredFlows.length === 0" class="empty-flows">
                <el-empty description="该项目暂无流程数据" />
              </div>
              <div
                v-else
                v-for="flow in filteredFlows"
                :key="flow.id"
                class="flow-item"
                :class="{ active: selectedFlow?.id === flow.id }"
                @click="selectFlow(flow)"
              >
                <div class="flow-info">
                  <div class="flow-name">{{ flow.flowName }}</div>
                  <div class="flow-content">{{ flow.workContent }}</div>
                </div>
                <el-icon v-if="selectedFlow?.id === flow.id" class="selected-icon">
                  <Check />
                </el-icon>
              </div>
            </el-scrollbar>
          </div>
        </div>
      </div>

      <!-- 对话框底部按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleConfirm" :disabled="!selectedProject || !selectedFlow"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, getCurrentInstance } from 'vue';
import { ElMessage } from 'element-plus';
import { ArrowDown, Search, Check } from '@element-plus/icons-vue';
import { listProInfoForQuery } from '@/api/project/init/proInfo';
import { listProFlowForQuery } from '@/api/project/plan/flow';
import type { ProInfoVO } from '@/api/project/init/proInfo/types';
import type { ProFlowVO } from '@/api/project/plan/flow/types';

// 定义组件属性
interface Props {
  modelValue?: {
    projectId?: string | number;
    projectName?: string;
    flowId?: string | number;
    flowName?: string;
  } | null;
  placeholder?: string;
  disabled?: boolean;
}

// 定义事件
interface Emits {
  (e: 'update:modelValue', value: Props['modelValue']): void;
  (e: 'change', value: Props['modelValue']): void;
}

const props = withDefaults(defineProps<Props>(), {
  placeholder: '请选择项目流程',
  disabled: false
});

const emit = defineEmits<Emits>();

// 获取 proxy 实例
const { proxy } = getCurrentInstance() as any;

// 响应式数据
const dialogVisible = ref(false);
const projectLoading = ref(false);
const flowLoading = ref(false);
const projectSearchKeyword = ref('');
const flowSearchKeyword = ref('');

const projectList = ref<ProInfoVO[]>([]);
const flowList = ref<ProFlowVO[]>([]);
const selectedProject = ref<ProInfoVO | null>(null);
const selectedFlow = ref<ProFlowVO | null>(null);

// 计算属性
const displayText = computed(() => {
  if (props.modelValue?.projectName && props.modelValue?.flowName) {
    return `${props.modelValue.projectName} - ${props.modelValue.flowName}`;
  }
  return '';
});

const filteredProjects = computed(() => {
  if (!projectSearchKeyword.value) {
    return projectList.value;
  }
  return projectList.value.filter(
    (project) =>
      project.proName.toLowerCase().includes(projectSearchKeyword.value.toLowerCase()) ||
      project.proNumber.toLowerCase().includes(projectSearchKeyword.value.toLowerCase())
  );
});

const filteredFlows = computed(() => {
  if (!flowSearchKeyword.value) {
    return flowList.value;
  }
  return flowList.value.filter(
    (flow) =>
      flow.flowName.toLowerCase().includes(flowSearchKeyword.value.toLowerCase()) ||
      (flow.workContent && flow.workContent.toLowerCase().includes(flowSearchKeyword.value.toLowerCase()))
  );
});

// API 调用方法
const fetchProjectList = async () => {
  try {
    projectLoading.value = true;
    const response = await listProInfoForQuery();

    projectList.value = response.data || [];
  } catch (error) {
    console.error('获取项目列表失败:', error);
    ElMessage.error('获取项目列表失败');
  } finally {
    projectLoading.value = false;
  }
};

const fetchFlowList = async (projectId: string | number) => {
  try {
    flowLoading.value = true;
    const response = await listProFlowForQuery({
      proId: projectId,
      pageNum: 1,
      pageSize: 1000
    });

    flowList.value = response.data || [];
  } catch (error) {
    console.error('获取项目流程失败:', error);
    ElMessage.error('获取项目流程失败');
  } finally {
    flowLoading.value = false;
  }
};

// 事件处理方法
const openDialog = () => {
  if (props.disabled) return;
  dialogVisible.value = true;
  if (projectList.value.length === 0) {
    fetchProjectList();
  }
};

const handleClose = () => {
  dialogVisible.value = false;
  // 重置搜索关键词
  projectSearchKeyword.value = '';
  flowSearchKeyword.value = '';
};

const selectProject = async (project: ProInfoVO) => {
  selectedProject.value = project;
  selectedFlow.value = null;
  flowList.value = [];

  // 获取该项目下的流程列表
  await fetchFlowList(project.id);
};

const selectFlow = (flow: ProFlowVO) => {
  selectedFlow.value = flow;
};

const handleConfirm = () => {
  if (!selectedProject.value || !selectedFlow.value) {
    ElMessage.warning('请选择项目和流程');
    return;
  }

  const value = {
    projectId: selectedProject.value.id,
    projectName: selectedProject.value.proName,
    flowId: selectedFlow.value.id,
    flowName: selectedFlow.value.flowName
  };

  emit('update:modelValue', value);
  emit('change', value);

  handleClose();
  ElMessage.success('选择成功');
};

const handleProjectSearch = () => {
  // 搜索逻辑在计算属性中处理
};

const handleFlowSearch = () => {
  // 搜索逻辑在计算属性中处理
};

// 监听 modelValue 变化，初始化选中状态
watch(
  () => props.modelValue,
  async (newValue) => {
    if (newValue?.projectId && newValue?.flowId) {
      // 如果有初始值，需要设置对应的选中状态
      if (projectList.value.length === 0) {
        await fetchProjectList();
      }

      const project = projectList.value.find((p) => p.id == newValue.projectId);
      if (project) {
        selectedProject.value = project;
        await fetchFlowList(project.id);

        const flow = flowList.value.find((f) => f.id == newValue.flowId);
        if (flow) {
          selectedFlow.value = flow;
        }
      }
    }
  },
  { immediate: true }
);

// 使用字典（需要根据实际情况调整）
const { project_type } = proxy?.useDict('project_type') || { project_type: ref([]) };

onMounted(() => {
  // 组件挂载时的初始化逻辑
});
</script>

<style lang="scss" scoped>
.project-flow-selector {
  width: 100%;
}

.selector-container {
  display: flex;
  gap: 20px;
  height: 500px;
}

.project-section,
.flow-section {
  flex: 1;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;

  h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }
}

.project-list,
.flow-list {
  padding: 12px;
}

.project-item,
.flow-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  margin-bottom: 8px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;

  &:hover {
    border-color: #409eff;
    background-color: #ecf5ff;
  }

  &.active {
    border-color: #409eff;
    background-color: #e6f4ff;
  }

  &:last-child {
    margin-bottom: 0;
  }
}

.project-info,
.flow-info {
  flex: 1;
  min-width: 0;
}

.project-name,
.flow-name {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.project-number {
  font-size: 12px;
  color: #909399;
  margin-bottom: 6px;
}

.flow-content {
  font-size: 13px;
  color: #303133;
  margin-top: 8px;
  line-height: 1.5;
  word-wrap: break-word;
  max-height: 3em;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.project-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  color: #909399;
}

.project-amount {
  color: #f56c6c;
  font-weight: 600;
}

.selected-icon {
  color: #409eff;
  font-size: 18px;
  margin-left: 8px;
}

.empty-flows {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

// 响应式设计
@media (max-width: 768px) {
  .selector-container {
    flex-direction: column;
    height: auto;
  }

  .project-section,
  .flow-section {
    height: 300px;
  }
}
</style>
